package visiopuce.DAO;

import java.math.BigDecimal;
import java.util.List;

import org.hibernate.Query;

import visiopuce.HibernateUtil;
import visiopuce.objets.Champ;

public class ChampDAOImpl extends GenericDAOImpl<Champ, BigDecimal> implements ChampDAO {
	/** Constructeur priv� */
	private ChampDAOImpl() {
	}

	/** Instance unique non pr�initialis�e */
	private static ChampDAOImpl INSTANCE = null;

	/** Point d'acc�s pour l'instance unique du singleton */
	public static ChampDAO getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new ChampDAOImpl();
		}
		return INSTANCE;
	}

	public Champ getChampByTypeAndIdObjet(String type, String idObjet) {
		String sql = "SELECT c FROM Champ c WHERE c.idObjet LIKE :idObjet AND c.type like :type ORDER BY c.idChamp DESC";
		Query query = HibernateUtil.getSession().createQuery(sql).setParameter("idObjet", idObjet).setParameter("type", type);
		query.setMaxResults(1);
		return findOne(query);
	}

	public void deleteAllByidObjet(String idObjet) {
		String sql = "DELETE FROM Champ c WHERE c.idObjet LIKE :idObjet";
		Query query = HibernateUtil.getSession().createQuery(sql).setParameter("idObjet", idObjet);
		query.executeUpdate();

	}

	@Override
	public String getSexeFoetusByIdPuce(int idPuce) {
		String sexe = null;
		String sql = "SELECT c.valeur FROM Champ c WHERE c.type like :type AND c.idObjet LIKE :idObjet";
		String sql2 = "SELECT p.analyse.prelevement.idPrelevement FROM Puce p WHERE p.idPuce = :idPuce";
		Query query1 = HibernateUtil.getSession().createQuery(sql2).setParameter("idPuce", idPuce);
		Integer idPrel = (Integer) query1.uniqueResult();

		Query query = HibernateUtil.getSession().createQuery(sql).setParameter("idObjet", "Prel-" + idPrel).setParameter("type", "tSexeFoetus");
		List<String> champs = (List<String>) query.list();
		if (champs.size() > 0) {
			sexe = champs.get(0);
		}
		return sexe;
	}

	@Override
	public List<Champ> getChampIdObjet(String idObj) {
		String sql = "SELECT c FROM Champ c WHERE  c.idObjet LIKE :idObjet ORDER BY c.idChamp DESc";
		Query query = HibernateUtil.getSession().createQuery(sql).setParameter("idObjet", idObj);
		return findMany(query);
	}
}
